package com.huan.xunlei1;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTask implements Runnable{
    private static Logger logger = Logger.getLogger(DownloadTask.class.getName());//日志记录器
    private int i;//线程编号
    private long fileSize;//文件总大小
    private int cpuNum;//线程数
    private long blockSize;//每个线程要下载的字节数
    private String url;//下载文件的url
    private String path;//文件保存的位置
    private DownloadedSizeNotify downloadSizeNotify;//下载进度通知接口

    public DownloadTask(int i, long fileSize, int cpuNum, long blockSize, String url, String path, DownloadedSizeNotify downloadSizeNotify) {
        this.i = i;
        this.fileSize = fileSize;
        this.cpuNum = cpuNum;
        this.blockSize = blockSize;
        this.url = url;
        this.path = path;
        this.downloadSizeNotify = downloadSizeNotify;
    }


    @Override
    public void run() {
        //计算线程的起始位置和终止位置
        long startPos = i*blockSize;
        long endPos = startPos+blockSize-1;
        //随机数访问文件
        RandomAccessFile randomAccessFile = null;
        BufferedInputStream bufferedInputStream = null;
        try{
            //让RandomAccessFile在指定位置开始写
            randomAccessFile = new RandomAccessFile(path,"rw");
            randomAccessFile.seek(startPos);
            //开始下载 range请求头
            URL url1 = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Range","bytes="+startPos+"-"+endPos);
            connection.setConnectTimeout(3000);

            connection.connect();

            bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            byte[] bytes = new byte[1024*1024];
            int length = -1;
            while ((length = bufferedInputStream.read(bytes,0,bytes.length))!=-1){
                randomAccessFile.write(bytes,0,length);
                if (downloadSizeNotify!=null){
                    downloadSizeNotify.notifySize(length);
                }
            }
            logger.info("线程"+i+"下载完成");
        }catch(Exception e){
            e.printStackTrace();
            logger.error("下载异常："+e.getMessage());
        }finally {
            if (bufferedInputStream!=null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (randomAccessFile!=null){
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
